<template>
  <div class="user-list">
    <el-card>
      <template #header>
        <div class="card-header">
          <div class="search-box">
            <el-input
              v-model="searchQuery"
              placeholder="搜索用户名/姓名"
              clearable
              @clear="handleSearch"
              @keyup.enter="handleSearch"
            >
              <template #append>
                <el-button @click="handleSearch">
                  <el-icon>
                    <Search />
                  </el-icon>
                </el-button>
              </template>
            </el-input>
          </div>
          <el-button type="primary" @click="handleAdd">新增用户</el-button>
        </div>
      </template>

      <el-table :data="userList" v-loading="loading" border style="width: 100%">
        <el-table-column type="index" width="55" label="序号" />
        <el-table-column prop="Username" label="用户名" />
        <el-table-column prop="RealName" label="姓名" />
        <el-table-column prop="Role" label="角色">
          <template #default="{ row }">
            <el-tag :type="row.Role === 0 ? 'danger' : 'success'">
              {{ row.Role === 0 ? "管理员" : "用户" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="Email" label="邮箱" min-width="165" />
        <el-table-column prop="Phone" label="手机号" min-width="115" />
        <el-table-column prop="Status" label="状态">
          <template #default="{ row }">
            <el-tag :type="row.Status ? 'success' : 'danger'">
              {{ row.Status ? "正常" : "禁用" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="CreatedTime"
          label="创建时间"
          min-width="130"
          show-overflow-tooltip
        />
        <el-table-column label="操作" width="250">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)"
              >编辑</el-button
            >
            <el-button type="primary" link @click="handleResetPassword(row)"
              >重置密码</el-button
            >
            <el-button type="danger" link @click="handleToggleStatus(row)">
              {{ row.Status ? "禁用" : "启用" }}
            </el-button>
            <el-button type="danger" link @click="handleDelete(row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          layout="total, sizes, prev, pager, next, jumper"
        />
      </div>
    </el-card>

    <!-- 新增/编辑用户对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增用户' : '编辑用户'"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="Username">
          <el-input
            v-model="formData.Username"
            :disabled="dialogType === 'edit'"
          />
        </el-form-item>
        <el-form-item label="姓名" prop="RealName">
          <el-input v-model="formData.RealName" />
        </el-form-item>
        <el-form-item label="角色" prop="Role">
          <el-select v-model="formData.Role" placeholder="请选择角色">
            <el-option label="管理员" :value="0" />
            <el-option label="用户" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="邮箱" prop="Email">
          <el-input v-model="formData.Email" />
        </el-form-item>
        <el-form-item label="手机号" prop="Phone">
          <el-input v-model="formData.Phone" />
        </el-form-item>
        <el-form-item v-if="dialogType === 'add'" label="密码" prop="Password">
          <el-input v-model="formData.Password" type="password" show-password />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 重置密码对话框 -->
    <el-dialog v-model="resetPasswordVisible" title="重置密码" width="400px">
      <el-form
        ref="resetPasswordFormRef"
        :model="resetPasswordForm"
        :rules="resetPasswordRules"
        label-width="100px"
      >
        <el-form-item label="新密码" prop="password">
          <el-input
            v-model="resetPasswordForm.Password"
            type="password"
            show-password
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="ConfirmPassword">
          <el-input
            v-model="resetPasswordForm.ConfirmPassword"
            type="password"
            show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="resetPasswordVisible = false">取消</el-button>
          <el-button type="primary" @click="handleResetPasswordSubmit"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Search } from "@element-plus/icons-vue";
import request from "../../utils/request";
import { userApi } from "../../api/userApi.js";

// 数据列表
const userList = ref([]);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const searchQuery = ref("");

// 对话框相关
const dialogVisible = ref(false);
const dialogType = ref("add");
const formRef = ref(null);
const formData = ref({});

// 表单验证规则
const rules = {
  Username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 3, max: 20, message: "长度在 3 到 20 个字符", trigger: "blur" },
  ],
  RealName: [{ required: true, message: "请输入姓名", trigger: "blur" }],
  Role: [{ required: true, message: "请选择角色", trigger: "change" }],
  Email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    { type: "email", message: "请输入正确的邮箱地址", trigger: "blur" },
  ],
  Phone: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号",
      trigger: "blur",
    },
  ],
  Password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, max: 20, message: "长度在 6 到 20 个字符", trigger: "blur" },
  ],
};

// 重置密码相关
const resetPasswordVisible = ref(false);
const resetPasswordFormRef = ref(null);
const resetPasswordForm = reactive({
  UserId: "",
  Password: "",
  ConfirmPassword: "",
});

// 重置密码验证规则
const resetPasswordRules = {
  Password: [
    { required: true, message: "请输入新密码", trigger: "blur" },
    { min: 6, max: 20, message: "长度在 6 到 20 个字符", trigger: "blur" },
  ],
  ConfirmPassword: [
    { required: true, message: "请确认密码", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (value !== resetPasswordForm.Password) {
          callback(new Error("两次输入的密码不一致"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
};

// 获取用户列表
const getUserList = async () => {
  loading.value = true;
  try {
    const res = await userApi.getUserList({
      pageNumber: currentPage.value,
      pageSize: pageSize.value,
      Username: searchQuery.value,
    });
    userList.value = res.result.data;
    total.value = res.result.total;
  } catch (error) {
    console.error("获取用户列表失败:", error);
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  getUserList();
};

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val;
  getUserList();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  getUserList();
};

// 新增用户
const handleAdd = () => {
  dialogType.value = "add";
  formData.value = {};
  dialogVisible.value = true;
};

// 编辑用户
const handleEdit = (row) => {
  dialogType.value = "edit";
  formData.value = row;
  dialogVisible.value = true;
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (dialogType.value === "add") {
          await userApi.addUser(formData.value);
          ElMessage.success("添加成功");
        } else {
          await userApi.updateUser(formData.value);
          ElMessage.success("更新成功");
        }
        dialogVisible.value = false;
        getUserList();
      } catch (error) {
        console.error("保存用户失败:", error);
      }
    }
  });
};

// 重置密码
const handleResetPassword = (row) => {
  resetPasswordForm.UserId = row.UserId;
  resetPasswordForm.Password = "";
  resetPasswordForm.ConfirmPassword = "";
  resetPasswordVisible.value = true;
};

// 提交重置密码
const handleResetPasswordSubmit = async () => {
  if (!resetPasswordFormRef.value) return;
  await resetPasswordFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await userApi.resetPassword(resetPasswordForm.UserId, {
          NewPassword: resetPasswordForm.Password,
        });
        ElMessage.success("密码重置成功");
        resetPasswordVisible.value = false;
      } catch (error) {
        console.error("重置密码失败:", error);
      }
    }
  });
};

// 切换用户状态
const handleToggleStatus = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要${row.Status ? "禁用" : "启用"}该用户吗？`,
      "提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );
    console.log(row);

    await userApi.updateStatus({
      UserId: row.UserId,
      Status: row.Status ? false : true,
    });
    ElMessage.success(`${row.Status ? "禁用" : "启用"}成功`);
    getUserList();
  } catch (error) {
    if (error !== "cancel") {
      console.error("切换用户状态失败:", error);
    }
  }
};

// 删除用户
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm("确定要删除该用户吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });
    await request({
      url: `/user/${row.id}`,
      method: "delete",
    });
    ElMessage.success("删除成功");
    getUserList();
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除用户失败:", error);
    }
  }
};

onMounted(() => {
  getUserList();
});
</script>

<style scoped>
.user-list {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-box {
  width: 300px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
